package gui

import (
	"fyne.io/fyne/v2"
	"fyne.io/fyne/v2/container"
	"fyne.io/fyne/v2/dialog"
	"fyne.io/fyne/v2/widget"
	"github.com/sirupsen/logrus"
	"treesize/src/org/ligson/treesize/util"
)

type FileTree struct {
	widget.Tree
}

func loadData(path string, fileTree *FileTree) map[string]*util.MyFileInfo {
	logrus.Info("打开目录" + path)
	loadingDlg := dialog.NewInformation("提示", "计算中...", w)
	loadingDlg.Show()
	var fileMap map[string]*util.MyFileInfo = make(map[string]*util.MyFileInfo)
	util.CalcDirSize(path, 1, fileMap)
	loadingDlg.Hide()

	fileTree.Root = path
	fileTree.ChildUIDs = func(uid widget.TreeNodeID) (c []widget.TreeNodeID) {
		if uid == "" {
			c = util.GetFileList(path, fileMap)
		} else {
			c = util.GetFileList(uid, fileMap)
		}
		return c
	}
	fileTree.IsBranch = func(uid widget.TreeNodeID) (ok bool) {
		return util.IsDir(uid)
	}

	fileTree.CreateNode = func(branch bool) (o fyne.CanvasObject) { // tree 添加控件的

		return container.NewGridWithColumns(2, NewTreeLabel("name", "1"), NewTreeLabel("size", "1"))
		//return container.NewBorder(nil, nil, text, size)
		//return size
	}

	fileTree.UpdateNode = func(uid widget.TreeNodeID, branch bool, node fyne.CanvasObject) {
		//startTime := time.Now().UnixMilli()
		containers := node.(*fyne.Container)

		myFile := fileMap[uid]
		textLbl := containers.Objects[0].(*TreeLabel)
		textLbl.SetText(myFile.File.Name())
		textLbl.Path = uid
		//sizeLbl := TreeLabel{}
		var fileSize int64 = myFile.Size
		sizeLbl := containers.Objects[1].(*TreeLabel)
		sizeLbl.SetText(util.FormatBytes(fileSize))
		sizeLbl.Path = uid

		//endTime := time.Now().UnixMilli()
		//logrus.Info("更新节点" + uid + "花费时间(ms):" + strconv.FormatInt(endTime-startTime, 10))

	}

	fileTree.Refresh() // 刷新tree

	return fileMap
}
func NewFileTree() *FileTree {

	fileTree := &FileTree{}
	fileTree.ChildUIDs = nil
	fileTree.IsBranch = nil
	fileTree.CreateNode = nil
	fileTree.UpdateNode = nil
	fileTree.ExtendBaseWidget(fileTree)

	return fileTree
}

func (m *FileTree) TappedSecondary(e *fyne.PointEvent) {
	logrus.Infof("--x:%f---y:%f\n", e.Position.X, e.Position.Y)
}
